#include "netdisk.h"
//版本1 创建一个文件夹，创建成功返回0，创建失败返回errno
int mkdir_1(const char *dir1 ,char *pdir ) { 
    char subpath[256] = {0};
    sprintf(subpath,"%s/%s",pdir,dir1);
    mode_t mode;
    sscanf("0777","%o",&mode);
    int ret = mkdir(subpath,mode);
    if(ret == 0)
        return 0;
    else
        return errno;
}
//版本2，一次性创建多个文件夹,不支持递归创建，0表示全部创建成功，否则返回最后一个失败的errno
int mkdirFunc(const char *dir1 ,Stack_t pdir ) {
    char str[1024];
    strcpy(str,dir1);
    int idx = 0;
    char *p[1024];
    p[idx++] = strtok(str," ");
    //printf("%s\n",p[0]);
    while((p[idx++] = strtok(NULL," ")) != NULL);
    //printf("%s\n",p[idx-1]);
    char subpath[256] = {0};
    int ret = 0;
    for(int i = 0; i < idx && p[i] != NULL; i++)
    {
        //需要在此处循环调用onePath函数，得到拼接好的路径
        onePath(p[i],subpath, &pdir);
        //sprintf(subpath,"%s/%s",pdir,p[i]);
        //printf("%s\n",subpath);
        mode_t mode;
        sscanf("0777","%o",&mode);
        int retVal = mkdir(subpath,mode);
        if(retVal == -1)
            ret = -1;
    }
    return ret;
}
//#include "head.h"
//版本1，只删除1个目录,0表示删除成功，-1表示删除失败
int rmdir_1(const char *dir1 ,char *pdir ) {
    //char *p = getpwd();
    char subpath[256] = {0};
    sprintf(subpath,"%s/%s",pdir,dir1);
    int ret = rmdir(subpath);
    return ret;//0表示删除成功，-1表示删除失败
}

//版本2 删除多个空目录,支持递归删除，0表示全部删除成功，-1表示存在删除失败,
int rmdirFunc(const char *dir1 , Stack_t pdir ) {
    char str[1024];
    strcpy(str,dir1);
    int idx = 0;
    char *p[1024];
    p[idx++] = strtok(str," ");
    //printf("%s\n",p[0]);
    while((p[idx++] = strtok(NULL," ")) != NULL)
        //printf("%s\n",p[idx-1]);
    printf("%d\n",idx);
    char subpath[256] = {0};
    int ret = 0;
    for(int i = 0; i < idx && p[i] != NULL; i++)
    {
        //需要在此处循环调用onePath函数，得到拼接好的路径
        onePath(p[i],subpath,&pdir);
        //sprintf(subpath,"%s/%s",pdir,p[i]);
        //printf("%s\n",subpath);
        int retVal = rmdir(subpath);
        if(retVal == -1)
            ret = -1;


    }
    return ret;//0表示删除成功，-1表示删除失败
}
//版本一，删除一个文件
int remove_1(const char *filename, char *pdir)
{
    char subpath[256] = {0};
    sprintf(subpath,"%s/%s",pdir,filename);
    int retVal = unlink(subpath);
    if(retVal == -1)
        return errno;
}

//版本二，删除多个文件，支持递归删除，全部成功删除返回0，否则返回最后一个失败的1
int removeFunc(const char *filename, Stack_t pdir)
{
    char str[1024];
    strcpy(str,filename);
    int idx = 0;
    char *p[1024];
    p[idx++] = strtok(str," ");
    //printf("%s\n",p[0]);
    while((p[idx++] = strtok(NULL," ")) != NULL);
    //printf("%s\n",p[idx-1]);
    char subpath[256] = {0};
    int ret = 0;
    for(int i = 0; i < idx && p[i] != NULL; i++)
    {
        //需要在此处循环调用onePath函数，得到拼接好的路径
        onePath(p[i],subpath, &pdir);
        //sprintf(subpath,"%s/%s",pdir,p[i]);
        //printf("%s\n",subpath);
        int retVal = unlink(subpath);
        if(retVal == -1)
            ret = -1;
    }
    return ret;
}

